<template>
  <div>
    <el-table
      ref="myTable"
      :height="tableHeight"
      :data="data"
      @mouseenter="stopAutoScroll"
      @mouseleave="startAutoScroll"
    >
      <el-table-column type="index" width="50" />
      <el-table-column v-for="col in columns" :prop="col.id" :key="col.id" :label="col.label" :width="col.width">
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup lang="ts">
import { TableInstance } from 'element-plus';

interface IData {
  name: string;
  address: string;
}

interface IColumn {
  id: string;
  label: string;
  width?: number | string;
}

const data = ref<IData[]>([
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' },
  { name: 'John Doe', address: '123 Main St' }
]);

const columns = ref<IColumn[]>([
  { id: 'name', label: 'Name' },
  { id: 'address', label: 'Address' }
]);

let interval = ref(); // 定时器
const time = ref(100); // 滚动时间间隔
const scrollStep = ref(2); // 每次滚动的像素数
const tableHeight = ref(200); // 表格高度
const myTable = ref<TableInstance>(); // 表格实例

onMounted(() => {
  startAutoScroll();
});
onUnmounted(() => {
  clearInterval(interval.value);
});

const startAutoScroll = () => {
  // 开启自动滚动函数
  if (myTable.value) {
    interval.value = setInterval(() => {
      if (myTable.value) {
        const wapper = myTable.value.$el.querySelector('.el-scrollbar__wrap');
        wapper.scrollTop += scrollStep.value;
        if (wapper.scrollTop + wapper.clientHeight >= wapper.scrollHeight) {
          // 滚动到底部时重置位置
          wapper.scrollTop = 0;
        }
      }
    }, time.value);
  }
};

const stopAutoScroll = () => {
  // 停止自动滚动函数
  clearInterval(interval.value);
};
</script>

<style scoped></style>
